// pages/result/result.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    styleConf:{},
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    drawData: {},
    staticImgUrl: '',
    fontScale: false, // 字体是否压扁
    shareData: null,
    imgurl: '',
    shareImgPath: '',
    canvasHidden: true,
    showLoading: true,
    loadCloudCount: 0,
    hasShareImg: false, // 是否已有分享图片
    shareImgFlag: true // 防止多次长按页面
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      staticImgUrl: app.globalData.staticImgUrl,
      shareData: app.globalData.shareData
    })
    if (wx.canIUse('loadFontFace')) this.importFont()
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      this.getCloudDrawData()
    } else if (this.data.canIUse) {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          this.getCloudDrawData()
        }
      })
    } else {
      console.log('userInfo未授权')
    }
  },
  onReady() {
  },
  importFont() {
    let source = "url('https://content.igola.com/static/WECHATAPP/images/common/butterFont.ttf')"
    wx.loadFontFace({
      family: 'butterJS',
      source: source,
      success: (res) => {
        console.log('外部字体引用成功', res)
        this.setData({
          fontScale: true
        })
      },
      fail: (res) => {
        console.log('外部字体引用失败', res)
        this.setData({
          fontScale: false
        })
      }
    })
  },
  getCloudDrawData() {
    let type = 'career'
    let functionName = 'draw_male'
    if (app.globalData.drawData && app.globalData.drawData.type) type = app.globalData.drawData.type
    wx.cloud.init()
    if (this.data.userInfo.gender == 2) functionName = 'draw_female'
    wx.cloud.callFunction({
      name: functionName,
      data: {
        type: type
      },
      success: res => {
        console.log('云端数据调用成功', res)
        this.getDrawResult(res.result.drawData.data[0])
      },
      fail: err => {
        console.log('云端数据调用失败', err)
        this.data.loadCloudCount++
        if (this.data.loadCloudCount > 1) {
          wx.showModal({
            title: '提示',
            content: '网络出错，请稍后重试',
            showCancel: false,
            confirmText: '返回首页',
            confirmColor: '#EE7942',
            success: (res) => {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../index/index'
                })
              }
            }
          })
        } else {
          wx.showLoading({
            title: '网络开小差~请稍等',
            success: (res) => {
              this.onLoad()
            }
          })
          setTimeout(function () {
            wx.hideLoading()
          }, 2000)
        }
      }
    })
  },
  getDrawResult(result) {
    if (!app.globalData.drawData) app.globalData.drawData = {}
    app.globalData.drawData.name = result.name
    app.globalData.drawData.result = result.tags[Math.floor(Math.random() * (result.tags.length))]
    app.globalData.drawData.type = result.type
    if (app.globalData.drawData) {
      this.setData({
        drawData: app.globalData.drawData
      })
      this.setData({
        "styleConf.imgurl": app.globalData.staticImgUrl + this.data.drawData.type + '@2x.jpg'
      })
      switch (this.data.drawData.type) {
        case "career": this.setData({ "styleConf.color": "#3C329B" })
          break
        case "wealth": this.setData({ "styleConf.color": "#DCB450" })
          break
        case "healthy": this.setData({ "styleConf.color": "#9B3232" })
          break
        case "marriage": this.setData({ "styleConf.color": "#C85AAA" })
          break
      }
    }
    this.getImgUrl()
    setTimeout(() => {
      this.setData({
        showLoading: false
      })
    }, 3000)
  },
  getImgUrl() {
    wx.getImageInfo({
      src: this.data.staticImgUrl + this.data.drawData.type + '@2x.jpg',
      success: (res) => {
        console.log('图片加载成功', res)
        this.setData({
          imgurl: res.path
        });
      }
    })
    wx.getImageInfo({
      src: this.data.staticImgUrl + 'draw-lots-QR.jpg',
      success: (res) => {
        console.log('图片加载成功', res)
        this.setData({
          QRimgurl: res.path
        });
      }
    })
    wx.getImageInfo({
      src: this.data.userInfo.avatarUrl,
      success: (res) => {
        console.log('图片加载成功', res)
        this.setData({
          avatarUrl: res.path
        });
      }
    })
  },
  // 绘制多行文本
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth, fontHeight, type) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    var strLen = str.length
    var y = initHeight + (5 - str.length) * 20      
    if (strLen > 5) {
      y = initHeight
    }
    if (type == 'column') {
      for (let i = 0; i < str.length; i++) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, y);
        y += fontHeight;
        lastSubStrIndex = i;
        titleHeight += 30;
        if (i == str.length - 1) { //绘制剩余部分
          ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, y);
        }
      }
    } else {
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        // lineWidth += 18
        if (lineWidth > canvasWidth) {
          ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
          initHeight += fontHeight;
          lineWidth = 0;
          lastSubStrIndex = i;
          titleHeight += 30;
        }
        if (i == str.length - 1) { //绘制剩余部分
          ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
        }
      }
    }
    
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },
  toShareImg() {
    if (this.data.shareImgFlag) {
      this.data.shareImgFlag = false
      this.drawShareImage()
    }
  },
  drawShareImage() {
    if (this.data.hasShareImg) {
      wx.previewImage({
        urls: [this.data.shareImgPath]
      })
      this.data.shareImgFlag = true
      return
    }
    wx.showLoading()
    if (!this.data.avatarUrl || !this.data.QRimgurl || !this.data.imgurl) {
      setTimeOut(() => {
        this.drawShareImage()
      }, 500)
      return
    }
    const ctx = wx.createCanvasContext('share')
    ctx.drawImage(this.data.imgurl, 0, 0, 318, 616)
    ctx.save()
    ctx.beginPath()
    ctx.arc(159, 112, 32, 0, Math.PI * 2, false);
    ctx.clip();
    ctx.drawImage(this.data.avatarUrl, 127, 80, 64, 64)
    ctx.restore()
    ctx.draw()

    ctx.drawImage(this.data.QRimgurl, 125, 515, 75, 75)

    ctx.setFontSize(18)
    ctx.setTextAlign('center')
    ctx.setTextBaseline('middle')
    ctx.setFillStyle(this.data.styleConf.color)
    this.drawText(ctx, this.data.drawData.result.detail, 159, 425, 145, 260, 25)

    ctx.setFontSize(13)
    ctx.setFillStyle('#000')
    ctx.setTextAlign('center')
    ctx.fillText('长按识别', 250, 545)
    ctx.fillText('二维码', 250, 563)

    ctx.font = 'normal bold 14px "PingFang SC", 微软雅黑, "Microsoft YaHei", sans-serif'
    ctx.setFillStyle(this.data.styleConf.color)
    ctx.setTextAlign('center')
    ctx.fillText(this.data.userInfo.nickName, 159, 160)
                                                                                             
    ctx.setFontSize(36)
    ctx.setFillStyle(this.data.styleConf.color)
    ctx.setTextAlign('center')
    ctx.setTextBaseline('middle')
    // ctx.scale(1.5, 1)
    this.drawText(ctx, this.data.drawData.result.name, 159, 160, 140, 35, 40, 'column')

    ctx.stroke()
    ctx.draw(true, () => {
      wx.canvasToTempFilePath({
        canvasId: 'share',
        x: 0,
        y: 0,
        width: 318,
        height: 616,
        success: (res) => {
          console.log('生成图片成功', res)
          this.setData({
            shareImgPath: res.tempFilePath
          })
          if (!res.tempFilePath) {
            wx.showModal({
              title: '提示',
              content: '图片绘制中，请稍后重试',
              showCancel: false
            })
          }
          wx.hideLoading()
          wx.previewImage({
            urls: [this.data.shareImgPath]
          })
          this.data.shareImgFlag = true
          this.data.hasShareImg = true
          // wx.saveImageToPhotosAlbum({
          //   filePath: res.tempFilePath,
          //   success: (res) => {
          //     wx.hideLoading()
          //     console.log('图片保存成功 ', res)
          //     wx.showToast({
          //       title: '图片保存成功',
          //       duration: 2000
          //     })
          //     setTimeout(() => {
          //       wx.previewImage({
          //         urls: [this.data.shareImgPath]
          //       })
          //     }, 2000)
          //     this.data.shareImgFlag = true
          //   },
          //   fail: (err) => {
          //     wx.hideLoading()
          //     console.log('图片保存失败', err)
          //     wx.showToast({
          //       title: '图片保存失败',
          //       duration: 2000
          //     })
          //   }
          // })
        }
      })
    })
  },
  goToIndex() {
    wx.reLaunch({
      url: '../index/index'
    })
  },
  onShow() {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(url) {
    let shareData = this.data.shareData[Math.floor(Math.random() * 4)]
    return {
      title: shareData.text,
      imageUrl: shareData.imgUrl,
      path: 'pages/index/index'
    }
  }
})
